class Folder < ActiveRecord::Base
#  belongs_to removable_media
  belongs_to :parent, :class_name => "Folder", :foreign_key => :parent_id
  has_many :images, :dependent => :destroy
  has_many :children, :class_name => "Folder", :foreign_key => :parent_id, :dependent => :destroy
  has_many :scan_targets, :dependent => :destroy
  validates_uniqueness_of :path

  # Folders ought always be called by path using "Folder.find_or_create_by_path(path)". If path already exists, you will get an exception on save otherwise. You know, because of the validates_uniqueness_of :path above.
  # This method also ensures the existance of this folder's ancestry.

  def path=(new_path)
    raise "path= is a write-once method on Folder" unless(self.path.nil?)
    
    raise "Don't be feeding me a blank path" if(new_path.blank?)
    raise "No support for ~ (tilde) home folders" if(new_path[0,1] == '~')
    raise "Path must be absolute" unless(new_path[0,1] == '/')
    raise "No support for . or .. in path" unless(new_path[%r{/\.\.?/}].nil?)
    
    (parent_path, leaf) = File.split new_path
    if(leaf=='/' and parent!='/')   #Interestingly File.split is UNC aware.. but File.split "//a/b" gives you parent "//a/b" and leaf "/" .. backwards of what I want.
      leaf = parent_path # I'm not using this yet, but in case I do I'd like the value to be correct as expected. :3
      parent_path = '/'
    end
    
    # Set (or create) our parent. Yep, this recurses to the root if necessary.
    if(leaf == '/') # leaf == '/' means we are root, we have no parent.
      self.parent_id=0
    else
      self.parent = Folder.find_or_create_by_path(parent_path)
    end
    
    super
    
  end  
end
